package org.zachary.agent.infrastructure.service;


import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.zachary.agent.domain.aggregate_model.loginUser.LoginUser;
import org.zachary.agent.domain.aggregate_model.loginUser.Role;
import org.zachary.agent.infrastructure.repository.UserMapper;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper loginUserMapper;

    @Override
    public UserDetails loadUserByUsername(String uuid) throws UsernameNotFoundException {

        LoginUser loginUser = loginUserMapper.queryLoginByUuid(uuid);
        System.out.println("用户角色数量：" + loginUser.getRoles().size());

        if (loginUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //用户名不为空 那么需要把用户的信息交给security进行验证

        List<Role> roles = loginUser.getRoles();

        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            //把自己的角色数据 添加到security授权数据中
            //注意: 这里添加的权限是 ROLE_ 开头的
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        System.out.println("角色"+roles);
        System.out.println("权限"+authorities);

        //把用户名 密码 和授权数据移交给security
        return new User(loginUser.getUuid(),loginUser.getPassword(), authorities);
    }
}
